package com.fingard.dsp.bank.directbank.gzdsf01;

import java.io.File;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsUtils;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.io.FileHelper;
import com.fingard.net.WebRequest;
import com.fingard.net.listener.SocketReceiver;
import com.fingard.xml.XmlTextWriter;

public class GZDSF01AcceptNotice extends GZDSF01Base implements IAcceptNotice {
	@Override
	public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
    	NoticeResp resp = new NoticeResp();
		try{
			String p_req = pNtReq.getReqString();
	    	WriteBankLogLn("银行通知返回原始数据:\r\n" + pNtReq.getFullString());
			
			String encryptKey = getBankConfig().getValueAsString("encryptKey");
			WriteBankLogLn("通知密文解密密钥内容:" + encryptKey);
			
			if (p_req.length() > 9) {
				p_req = p_req.substring(9);
			}
			//WriteBankLogLn("通知密文解密前报文体内容:" + p_req);
			
	    	String tmpStrRet = new CfbsUtils(this.getSbLog()).txnDecSample(p_req, encryptKey, getCharset());
	    	WriteBankLogLn("通知密文解密后报文体数据明文:\r\n" + tmpStrRet);
	    	
	    	String transCode = tmpStrRet.substring(0, 6);
	    	if (GZDSF01TransCode.LOGIN.equals(transCode)) {
	    		String tmpOldToken = tmpStrRet.substring(58, 78).trim();
	    		String tmpNewToken = tmpStrRet.substring(78, 98).trim();
	    		String tmpRespCode = tmpStrRet.substring(98, 106).trim();
	    		//String transSeq = tmpStrRet.substring(10, 26).trim();
	    		if ("CT0I1000".equals(tmpRespCode)) {
	    			WriteBankLogLn("机构登录成功!\r\n旧登录标识："+tmpOldToken+"，新登录标识："+tmpNewToken);
	    			bankFront.token = tmpNewToken;
	    			bankFront.loginFlag = "true";
	    			bankFront.loginFailCount = 0;
	    		} else {
	    			bankFront.loginFailCount++;
	    			WriteBankLogLn("机构登录失败,原因:" + tmpRespCode+"，失败次数："+bankFront.loginFailCount);
	    		}
	    		String waitKey = tmpStrRet.substring(0, 26);
	    		WriteBankLogLn("setOne("+waitKey+")");
	    		this.bankFront.resetEvent.setOne(waitKey);
	    	} else if (GZDSF01TransCode.RECSIGN.equals(transCode)) {
                if (getBankConfig().getValueAsBool("isAccept630")) {
                    //上送630
                    String tmpRespCode = tmpStrRet.substring(77, 85).trim();
                    String respMsg= tmpStrRet.substring(530, 590).trim();
                    String infoCode = tmpRespCode;
                    String unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRespCode);
					String respInfo = getBankConfig().getMapDesByKey("contractMapping", tmpRespCode);

                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    xmlWriter.writeStartDocument();
                    xmlWriter.writeStartElement("ATSYH");
                    xmlWriter.writeStartElement("TransResp");
                    xmlWriter.writeElementString("BankCode", "GZDSF01");
                    xmlWriter.writeElementString("TransType", "ContractNotify");
                    xmlWriter.writeElementString("TransSeqID", "");
                    xmlWriter.writeStartElement("TransParam");
                    xmlWriter.writeStartElement("DetailRecord");
                    xmlWriter.writeElementString("RespCode", "0");
                    xmlWriter.writeElementString("RespInfo", infoCode+":"+respInfo);
                    xmlWriter.writeElementString("ReqSeqID", tmpStrRet.substring(10, 26).trim());
                    xmlWriter.writeElementString("PayAct", tmpStrRet.substring(388, 420).trim());
                    xmlWriter.writeElementString("SignDate", "");
                    xmlWriter.writeElementString("SourceNoteCode", "");
                    xmlWriter.writeElementString("PolicyNo", "");
                    xmlWriter.writeElementString("OppActName", "");
                    xmlWriter.writeElementString("CertType", "");
                    xmlWriter.writeElementString("CertNumber", "");
                    xmlWriter.writeElementString("CellPhone", "");
                    xmlWriter.writeElementString("CurType", "");
                    xmlWriter.writeElementString("NoteMoney", "");
                    xmlWriter.writeElementString("BusType", "");

                    if ("SC000".equals(unifiedCode) || "SC001".equals(unifiedCode)) {
                        xmlWriter.writeElementString("SignState", "success");
                    }else if ("IN001".equals(unifiedCode)){
                        xmlWriter.writeElementString("SignState", "signing");
                    }else {
                        xmlWriter.writeElementString("SignState", "fail");
                    }
                    xmlWriter.writeElementString("UnifiedCode", unifiedCode);
                    xmlWriter.writeElementString("AuthCode", tmpStrRet.substring(85, 145).trim());
                    xmlWriter.writeEndDocument();
                    String url = bankFront.getUrl("notifyURL");
                    WriteBankLogLn("通知630的地址：" + url);
                    String p_reqStr = xmlWriter.toXmlString();
                    WriteBankLogLn("通知630的报文：" + p_reqStr);
                    byte[] tmpToWriteBytes = p_reqStr.getBytes(getCharset());
                    WebRequest tmpWebRequest = new WebRequest(url);
                    tmpWebRequest.setConnectTimeout(600000);
                    tmpWebRequest.setRequestProperty("Content-Type", "application/xml");
                    tmpWebRequest.setRequestProperty("Connection", "keep-alive");
                    tmpWebRequest.upload(tmpToWriteBytes, getCharset());
                } else {
                    RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
                    tmpRetDetail.reqSeqID = tmpStrRet.substring(10, 26).trim();

                    tmpRetDetail.respCode = "0";
                    String tmpRespCode = tmpStrRet.substring(77, 85).trim();
                    String respInfo = getBankConfig().getMapDesByKey("contractMapping", tmpRespCode);
                    String respMsg= tmpStrRet.substring(530, 590).trim();
                    tmpRetDetail.infoCode = tmpRespCode;
                    tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRespCode);
                    if ("SC000".equals(tmpRetDetail.unifiedCode) || "SC001".equals(tmpRetDetail.unifiedCode)) {
                        tmpRetDetail.signState = "success";
                        tmpRetDetail.unifiedCode = "SC000";
                        tmpRetDetail.respInfo = "签约成功";
                    }else if ("IN001".equals(tmpRetDetail.unifiedCode)){
                        tmpRetDetail.signState = "ing";
                        tmpRetDetail.respInfo = "签约处理中";
                    }else {
                        tmpRetDetail.signState = "fail";
                        tmpRetDetail.respInfo = respInfo;
                    }
                    tmpRetDetail.authCode = tmpStrRet.substring(85, 145).trim();

                    XmlTextWriter xmlWriter = new XmlTextWriter();
                    tmpRetDetail.writeToXml(xmlWriter);
                    xmlWriter.writeEndElement();

                    String retAtsXml = xmlWriter.toXmlString()+"\r\n";
                    WriteBankLogLn("实时协议签约返回ATS相应数据:\r\n" + retAtsXml);
                    Date timeNow = new Date();
                    String tmpContractFilePath = getTempFileDirectory(timeNow) + File.separator + "Contract" + File.separator + Format.Date10Format.format(timeNow) + ".txt";

                    FileHelper.appendFile(tmpContractFilePath, retAtsXml, getCharset());
                    WriteBankLogLn("附加到文件:\r\n" + tmpContractFilePath);
                }
	    	} else if (GZDSF01TransCode.REALTIMEREC.equals(transCode)) {
	    		ReqRespHeader respHeader = new ReqRespHeader();
	    		respHeader.bankCode = "GZDSF01";
	    		respHeader.transType = "9108";
	    		RetAtsSingle retAts = new RetAtsSingle(respHeader);
	    		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
	    		tmpRetDetail.reqSeqID = tmpStrRet.substring(10, 26).trim();
	    		tmpRetDetail.respCode = "0";
	    		String tmpRespCode = new String(tmpStrRet.getBytes(getCharset()), 424, 8);
	    		tmpRetDetail.respInfo = getBankConfig().getMapValueByKey("payCodeMapping", tmpRespCode);
                tmpRetDetail.transState = tmpRespCode;
                tmpRetDetail.payInfoCode = tmpRespCode;
	            retAts.writeRetDetail(tmpRetDetail);
	            String tmpRespBody = retAts.getRetAtsString();
	            WriteBankLogLn("单笔交易查询返回ATS相应数据:\r\n" + tmpRespBody);
	            String tmpFilePath = getTempFileDirectory() + File.separator + "RealTimeRec" + File.separator + tmpRetDetail.reqSeqID + ".txt";
	            FileHelper.writeFile(tmpFilePath, tmpRespBody, getCharset());
            } else if (GZDSF01TransCode.REALTIMEPAY.equals(transCode)) {
                ReqRespHeader respHeader = new ReqRespHeader();
                respHeader.bankCode = "GZDSF01";
                respHeader.transType = "1908";
                RetAtsSingle retAts = new RetAtsSingle(respHeader);
                RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
                tmpRetDetail.reqSeqID = tmpStrRet.substring(10, 26).trim();
                tmpRetDetail.respCode = "0";
                String tmpRespCode = new String(tmpStrRet.getBytes(getCharset()), 425, 8);
                tmpRetDetail.respInfo = getBankConfig().getMapValueByKey("payCodeMapping", tmpRespCode);
                tmpRetDetail.transState = tmpRespCode;
                tmpRetDetail.payInfoCode = tmpRespCode;
                retAts.writeRetDetail(tmpRetDetail);
                String tmpRespBody = retAts.getRetAtsString();
                WriteBankLogLn("单笔交易查询返回ATS相应数据:\r\n" + tmpRespBody);
                String tmpFilePath = getTempFileDirectory() + File.separator + "REALTIMEPAY" + File.separator + tmpRetDetail.reqSeqID + ".txt";
                FileHelper.writeFile(tmpFilePath, tmpRespBody, getCharset());
	    	}else if (GZDSF01TransCode.HEARTBEAT.equals(transCode)) {
	    		String tmpRespCode = tmpStrRet.substring(34, 42).trim();
	    		WriteBankLogLn("接收到心跳响应包，返回码：" + tmpRespCode);
	    	}else{
	    		WriteBankLogLn("系统未处理的交易种类："+transCode);
	    	}
		}catch(Exception ex){
			this.WriteBankLogLn(ex);
		}
		resp.respBytes = "".getBytes(pNtReq.reqCharset);
    	return resp;
	}

	@Override
	public void getContentLength(SocketReceiver p_receiver) throws Exception {
		if (p_receiver.contentLength == -1) {
			if (p_receiver.readedLength >= 11) {
				String tmpHead = new String(p_receiver.reqBytes, 3, 8, getCharset());
				p_receiver.contentLength = Integer.parseInt(tmpHead.trim());
				p_receiver.contentStartIndex = 2;
			}
		}
	}
}
